﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using System.Threading;
using System.Collections;
using System.IO;
using Controller;

namespace Server
{
    public class Server
    {
        private Dictionary<String,Session> _sessions = new Dictionary<string, Session>();
        private Boolean _active = true;
        private FacadeController controller;
        
        public Server(int port, FacadeController controller)
        {
            Console.WriteLine("prøver at starte server på port : " + port);
            TcpListener listener = new TcpListener(IPAddress.Any,port);
            Console.WriteLine("server startet på port: "+port);
            this.controller = controller;
            listener.Start();
            while (_active)
            {
                Console.WriteLine("Server klar");
                //blokerende kald til 
                Socket clientSocket = listener.AcceptSocket();
                Console.WriteLine("client accepteret på port " + port + " med IP" + clientSocket.RemoteEndPoint);
                ClientHandler handler = new ClientHandler(clientSocket,this, controller);


                //ny tråd spawnes
                Thread clientThread = new Thread(handler.RunClient);
                clientThread.Start();
            }
        }

        public Session StartSession(String ip)   // ikke synkroniseret
        {
            Session nySession = new Session(ip);
            _sessions.Add(nySession.SessionId, nySession);

            return nySession;
        }

        public Session GetSession(String oldSessionID)
        {
            if (_sessions.ContainsKey(oldSessionID))
                return _sessions[oldSessionID];
            return null;
        }
    }
}
